import enquireJs from "enquire.js";
import moment from "moment"
import store from "@/store"
import { LocalStorageService } from './storage'
import { PACKAGE_NAME } from '@/config/const'

export function formatDate(v){
  return  v ? moment(v).format('YYYY-MM-DD') : null
}

export function valueOfDate(v){
  return v ? moment(v).valueOf() : null
}

/*
  时间选择器的快捷输入 - 模板
  模板 = {
    今天: [moment().startOf("day"), moment()],
    昨天: [moment().startOf("day").subtract(1, "days"), moment().startOf("day").subtract(1, "days")],
    最近一周: [moment().startOf("day").subtract(1, "weeks"), moment()],
    最近两周: [moment().startOf("day").subtract(2, "weeks"), moment()],
    最近1个月: [moment().startOf("day").subtract(1, "months"), moment()],
    最近3个月: [moment().startOf("day").subtract(3, "months"), moment()],
    最近半年: [moment().startOf("day").subtract(6, "months"), moment()],
    最近1年: [moment().startOf("day").subtract(1, "years"), moment()],
    本年度: [moment().startOf('year'), moment().startOf("day")]
  }
 */
// 时间选择器的快捷输入
export const DATA_RANGE = {
  近7天: [moment().startOf("day").subtract(1, "weeks"), moment()],
  近30天: [moment().startOf("day").subtract(1, "months"), moment()],
  近90天: [moment().startOf("day").subtract(3, "months"), moment()]
};

export function isDef(v) {
  return v !== undefined && v !== null;
}

/**
 * Remove an item from an array.
 */
export function remove(arr, item) {
  if (arr.length) {
    const index = arr.indexOf(item);
    if (index > -1) {
      return arr.splice(index, 1);
    }
  }
}

export function isRegExp(v) {
  return _toString.call(v) === "[object RegExp]";
}

export function enquireScreen(call) {
  const handler = {
    match: function() {
      call && call(true);
    },
    unmatch: function() {
      call && call(false);
    }
  };
  enquireJs.register("only screen and (max-width: 767.99px)", handler);
}

const _toString = Object.prototype.toString;

/**
 * 字典转换
 * @param data 列表数据
 * @param arr  转换字典集
 */
export function switchCode(data, arr) {
  data?.forEach(o => {
    arr.forEach(v => {
      let name = Object.keys(v)[0];
      o[name] = v[name].find(val => val.key === o[name])?.title;
    });
  });
}

/**
 * 处理特殊code 例如：code 为 0 的没有意义
 * @param obj 数据
 */
export function handleSpecialCode(obj) {
  for (let i in obj) {
    if (obj[i] === 0) {
      obj[i] = undefined;
    }
  }
}

/**
 * placeholder显隐转换
 * @param isDisabled 当前字段是否可点击
 * @param text 显示文字
 * @returns {String}
 */
export function changePlaceholder(isDisabled, text) {
  return isDisabled ? '' : text
}

/**
 * 获取默认跳转路径
 * @returns {String}
 */
export function getRedirectPath() {
  const redirectPath = localStorage.getItem('defaultPath') || '/enterprise';
  return redirectPath
}

/**
 * 获取当前按钮操作权限
 * @param page 对应页面
 * @returns {Boolean}
 */
export function getAuth(page) {
  let permissions = JSON.parse(localStorage.getItem('admin.permissions'));
  return permissions?.every(o => o.id !== page)
}

export function clearAMapKeys() {
  // 高德地图刷新页面影响有四个 localStorage的值，清除其中一个就可以
  localStorage.removeItem("_AMap_cvector")
  // localStorage.removeItem("_AMap_AMap.CustomLayer")
  // localStorage.removeItem("_AMap_anole") // 473k
  // localStorage.removeItem("_AMap_AMap.IndoorMap") // 94k
}

/**
 * TODO后续优化 获取初始跳转路径
 * @param resources 路由
 * @returns {Promise<AxiosResponse<T>}
 */
export function getInitPath(resources) {
  let prefixPath = resources[0]?.children[0]?.router;
  let suffixPath = resources[0]?.children[0]?.children[0]?.router;
  let path = '/' + prefixPath + (suffixPath ? '/' + suffixPath : '');
  localStorage.setItem('defaultPath', path);
  return path;
}

/**
 * 通用的校验程序
 * @param {*} form 表单
 * @param {*} isCertainField 表单
 */
export function commonValidate(form, certainField) {
  return new Promise((resolve) => {
    const attr = certainField ? 'validateField' : 'validate'
    if (!certainField) {
      form[attr]((valid) => {
        resolve(valid)
      })
      return
    }
    form[attr](certainField, (errorMessage) => {
      const valid = !errorMessage
      resolve(valid)
    })
  })
}
export const getDomain = () => {
  const { domain } = document
  const ip = /^(d+).(d+).(d+).(d+)$/
  const path = (ip.test(domain)) ? ('http://"+domain+":8080') : `http://${domain}`
  return path
}
/**
 * 逆向地理编码：将地理坐标（经纬度）转换成地址描述信息
 * @param arr 对应坐标[lng, lat]
 */

export const getGeocoderFn = async (arr, geocoder, callback) => {
  try {
    const cct = await geocoder.getAddress(arr, function (status, result) {
      if (status === "complete" && result.info === "OK") {
        if (result && result.regeocode) {
          callback(result);
        }
      }
    });
    return cct
  } catch (error) {
    throw new Error(error)
  }
}
// 正则限定输入
export function inputrule(val, reg) {
  let n = val.search(reg);
  if (n !== -1) return val.slice(0, n);
  return val;
}

/**
 * 获取websocket票据
 * @returns {String}
 */
export function getTicket() {
  let appId = process.env.VUE_APP_ID;
  let openId = store.getters["account/openId"] || "";
  let enterpriseId = store.getters["account/enterpriseId"] || "";
  let departmentId = store.getters["account/departmentId"] || "";
  let roleId = store.getters["account/roleId"] || "";
  let token = store.getters["account/token"] || "";

  let tk = `${token};${openId};${appId};${enterpriseId};${departmentId};${roleId}`;
  return tk;
}
/*
 * 同步vuex store数据
 * @param vuexStoreObject vuex json对象
 */
export const syncVuex = (vuexStoreObject) => {
  store.replaceState(vuexStoreObject || LocalStorageService.get(PACKAGE_NAME))
}
